package com.gmzg.gmzgnews.me.view;


import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ant.liao.GifView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.gmzg.gmzgnews.MainApplication;
import com.gmzg.gmzgnews.R;
import com.gmzg.gmzgnews.me.model.User;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.DbManager;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class MeFragment extends Fragment implements PlatformActionListener {

    private static final String TAG = MeFragment.class.getSimpleName();
    public static final String USER_IMAGE = "image";
    public static final String USERNAME = "username";
    public static final String SP_USER = "user";
    public static final String USER_ID = "id";
    public static final int REQUEST_CODE = 1;
    @BindView(R.id.qq_login)
    LinearLayout mQqLogin;
    @BindView(R.id.third_party_logins)
    LinearLayout mThirdPartyLogins;
    @BindView(R.id.weibo_login)
    LinearLayout mWeiboLogin;
    @BindView(R.id.weixin_login)
    LinearLayout mWeixinLogin;
    @BindView(R.id.head_portrait_iv)
    CircleImageView mHeadPortraitIv;
    @BindView(R.id.click_login_tv)
    TextView mClickLoginTv;
    @BindView(R.id.username_tv)
    TextView mUsernameTv;
    @BindView(R.id.loading_ll)
    LinearLayout mLoadingLl;
    @BindView(R.id.setting_iv)
    ImageView mSettingIv;
    @BindView(R.id.setting_tv)
    TextView mSettingTv;
    @BindView(R.id.gifView)
    GifView mGifView;
    @BindView(R.id.phoneNumber_tv)
    TextView mPhoneNumberTv;
    @BindView(R.id.setting)
    RelativeLayout mSetting;
    private DbManager db;
    private Application mContext;
    private SharedPreferences sp;


    public MeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity().getApplication();
        Fresco.initialize(mContext);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_me, container, false);
        ButterKnife.bind(this, view);


        //检查sharedPreference是否有已登陆信息
        getLoginState();
        Log.d(TAG, "过来了: ");
        db = ((MainApplication) mContext).getDb();
//        if (db != null) {
//            User user = new User();
//            user.setLoginType("qq");
//            user.setUsername("13287793220");
//            user.setPassword("123456");
//            try {
//                db.saveBindingId(user);
//            } catch (DbException e) {
//                e.printStackTrace();
//            }
//        }
        return view;
    }

    private void getLoginState() {
        sp = mContext.getSharedPreferences(SP_USER, mContext.MODE_PRIVATE);
        if (sp != null) {
            String username = sp.getString(USERNAME, null);
            String image = sp.getString(USER_IMAGE, null);
            if (username != null) {
                User user = new User();
                user.setImage(image);
                user.setUsername(username);
                loadLoginInfo(user);
            } else {
            }

        }
    }

    //实现第三方登录
    @OnClick({R.id.qq_login, R.id.setting_tv, R.id.phoneNumber_tv, R.id.setting_iv, R.id.weibo_login, R.id.weixin_login, R.id.click_login_tv})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.qq_login:
                //实现第三方QQ登陆，
                Log.d(TAG, "onClick: qq的登陆");
                thirdLogin(QQ.NAME);
                break;
            case R.id.weibo_login:
                Log.d(TAG, "realizeWeiboLogin: 微博的登陆");
                //实现第三方微博登陆：
                thirdLogin(SinaWeibo.NAME);
                break;
            case R.id.weixin_login:
                Log.d(TAG, "realizeWeixinLogin: 微信的登陆");
                thirdLogin(Wechat.NAME);
                break;
            case R.id.click_login_tv:
                intent = new Intent(getActivity(), LoginActivity.class);
                break;
            case R.id.setting_iv:
            case R.id.setting_tv:
                intent = new Intent(getActivity(), SettingActivity.class);
                break;
            case R.id.phoneNumber_tv:
                intent = new Intent(getActivity(), RegisterActivity.class);
                break;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }



    private void thirdLogin(String platformStr) {
        Platform platform = ShareSDK.getPlatform(getActivity().getApplication(), platformStr);
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }
        //设置false，表示使用SSO授权方式
        platform.SSOSetting(false);
        platform.showUser(null);//授权并获取用户信息
        platform.setPlatformActionListener(this);
        //设置gif动画图片
        mGifView.setGifImage(R.drawable.loading);
        mLoadingLl.setVisibility(View.VISIBLE);
    }


    //实现第三方登录需要的接口回调
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> map) {
        String platformName = platform.getName();
        User user = new User();
        if (SinaWeibo.NAME.equals(platformName)) {
            Log.d(TAG, "onComplete: 微博登陆成功");
            user = getUser(user, (String) map.get("name"), (String) map.get("avatar_large"), SinaWeibo.NAME);
            showLoginInfo(user);
        } else if (QQ.NAME.equals(platformName)) {
            Log.d(TAG, "onComplete: QQ登陆成功");
            user = getUser(user, (String) map.get("nickname"), (String) map.get("figureurl_qq_2"), QQ.NAME);
            showLoginInfo(user);
        } else if (Wechat.NAME.equals(platformName)) {
            Log.d(TAG, "onComplete: 微信登陆成功登陆成功");
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                Log.d(TAG, key + ":" + value);
            }
            user.setLoginType(Wechat.NAME);
        }
    }

    private User getUser(User user, String username, String image, String loginType) {
        user.setUsername(username);
        user.setImage(image);
        user.setLoginType(loginType);
        //将当前用户的信息保存到SharedPreferences中
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(USERNAME, user.getUsername());
        editor.putString(USER_IMAGE, user.getImage());
//        editor.putLong(USER_ID,user.getId());
        editor.apply();
        return user;
    }

    private void showLoginInfo(User user) {
        Observable
                .just(user)
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<User>() {
                    @Override
                    public void onCompleted() {
                        mLoadingLl.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(User user) {
                        loadLoginInfo(user);
                    }
                });
    }

    private void loadLoginInfo(User u) {
        String image = u.getImage();
        if (image != null) {
            if (image.startsWith("http:")) {
                Picasso.with(getActivity().getApplication())
                        .load(image)
                        .resize(200, 200)
                        .into(mHeadPortraitIv);
            } else {
                Uri uri = Uri.fromFile(new File(image));
                Picasso.with(getActivity())
                        .load(uri)
                        .resize(200, 200)
                        .into(mHeadPortraitIv);
            }

        }
        //隐藏“点击头像登陆”
        mUsernameTv.setText(u.getUsername());
        mUsernameTv.setVisibility(View.VISIBLE);
        mClickLoginTv.setVisibility(View.GONE);
        mPhoneNumberTv.setVisibility(View.INVISIBLE);
        mThirdPartyLogins.setVisibility(View.INVISIBLE);
        mSetting.setVisibility(View.VISIBLE);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        String platformName = platform.getName();
        if (SinaWeibo.NAME.equals(platformName)) {
            Log.d(TAG, "onError: 微博登陆失败" + throwable);
        } else if (QQ.NAME.equals(platformName)) {
            Log.d(TAG, "onError: QQ登陆失败" + throwable);
        } else if (Wechat.NAME.equals(platformName)) {
            Log.d(TAG, "onError: 微信登陆失败" + throwable);
        }
    }

    @Override
    public void onCancel(Platform platform, int i) {
        String platformName = platform.getName();
        if (SinaWeibo.NAME.equals(platformName)) {
            Log.d(TAG, "onError: 微博登陆取消");
        } else if (QQ.NAME.equals(platformName)) {
            Log.d(TAG, "onError: QQ登陆取消");
        } else if (Wechat.NAME.equals(platformName)) {
            Log.d(TAG, "onError: 微信登陆取消");
        }
    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEvent(Bundle bundle) {
//        if (bundle != null) {
//            User user = new User();
//            user.setUsername(bundle.getString(USERNAME));
//            user.setImage(bundle.getString(USER_IMAGE));
//            loadLoginInfo(user);
//        }
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(User user) {
        Log.d(TAG, "onEvent: 设置密码");
        getLoginState();
    }
     @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String user) {
        Log.d(TAG, "onEvent: 退出登录");
            //退出登录
            Picasso.with(getActivity())
                    .load(R.mipmap.bg)
                    .resize(200, 200)
                    .into(mHeadPortraitIv);
            //隐藏“点击头像登陆”
            mUsernameTv.setText("");
            mUsernameTv.setVisibility(View.INVISIBLE);
            mClickLoginTv.setVisibility(View.VISIBLE);
            mPhoneNumberTv.setVisibility(View.VISIBLE);
            mThirdPartyLogins.setVisibility(View.VISIBLE);
            mSetting.setVisibility(View.INVISIBLE);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
